<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
namespace core;
defined('BY_JYA') or exit('error');
//系统会员工具函数
class member{
	/*
		登陆
	*/
	public function login($mid){
		$_SESSION['member']=pdo_get('core_members',array('id'=>$mid),array('id','username','mobile','nickname','avatar','onemid'));
		$mid=$_SESSION['member']['onemid']>0?$_SESSION['member']['onemid']:$_SESSION['member']['id'];
		$_SESSION['uid']=$mid;
		publish('core','member.login',array('mid'=>$mid));
	}
	/*
		退出
	*/
	public function logout($mid){
		unset($_SESSION['uid'],$_SESSION['member']);
		publish('core','member.logout',array('mid'=>$mid));
	}
	/*
		确认企业员工
	*/
	public function check_worker(){
		$fans=pdo_get('core_fans',array('openid'=>$_SESSION['openid'],'uniacid'=>$_SESSION['uniacid'],'type'=>9),array('isworkman','mid'));
		if($fans['isworkman']){
			return true;
		}else{
			return false;
		}
	}
	/*
		注册
	*/
	public function register($member=array()){
		if($_SESSION['uid']){
			return $_SESSION['uid'];
		}
		if(!$member['uniacid']){
			$member['uniacid']=$_SESSION['uniacid'];
		}
		if($member['mobile'] && !$member['username']){
			$check=pdo_getcolumn('core_members',array('uniacid'=>$_SESSION['uniacid'],'username'=>$member['mobile']),'id');
			if(!$check){
				$member['username']=$member['mobile'];
			}
		}
		if(!$member['username']){
			do{
				$member['username']='user_'.random(10);
			}while(pdo_getcolumn('core_members',array('uniacid'=>$_SESSION['uniacid'],'username'=>$member['username']),'id'));
		}
		if(!$member['fromuser']){
			if($_SESSION['fromuser']){
				$member['fromuser']=$_SESSION['fromuser'];
			}
		}
		if(!$member['from_os']){
			$member['from_os']=get_os();
		}
		if(!$member['unionid'] && $_SESSION['unionid']){
			$member['unionid']=$_SESSION['unionid'];
		}
		if(!$member['createtime']){
			$member['createtime']=TIMESTAMP;
		}
		if($member['password']){
			$member['salt']=random(10);
			$member['password']=get_password(trim($member['password']),$member['salt']);
		}
		//如果密码，openid都为空就不能注册
		if(!$member['mobile'] && !$member['password'] && !$_SESSION['openid']){
			return true;
		}
		pdo_insert('core_members',$member);
		$uid=pdo_insertid();
		if($_SESSION['openid']){
			if($_SESSION['os']=='mobile' || $_SESSION['container']=='wechat'){
				if($_SESSION['container']=='wechat'){
					//微信环境
					$fans=pdo_get('core_fans',array('uniacid'=>$_SESSION['uniacid'],'type'=>2,'wxgid'=>$_SESSION['wechat_id'],'openid'=>$_SESSION['openid']),array('id','mid','unionid','avatar','nickname','sex'));
					$checkid=0;
					//先判断是不是关联公众号
					if($fans['unionid']){
						$member=pdo_get('core_members',array('id <>'=>$uid,'uniacid'=>$_SESSION['uniacid'],'unionid'=>$fans['unionid']),array('id','onemid'));
						$checkid=$member['onemid']>0?$member['onemid']:$member['id'];
					}
					if($fans['mid'] && !$checkid){
						$checkid=pdo_getcolumn('core_members',array('id'=>$fans['mid']),'id');
					}					
					if($fans['id'] && !$checkid){
						pdo_update('core_fans',array('mid'=>$uid),array('uniacid'=>$_SESSION['uniacid'],'id'=>$fans['id']));
						if($fans['avatar'] && $fans['nickname']){
							$member=pdo_get('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$uid),array('nickname','avatar','sex'));
							$member_update=array();
							if(!$member['nickname']){
								$member_update['nickname']=$fans['nickname'];
							}
							if(!$member['avatar']){
								$member_update['avatar']=$fans['avatar'];
							}
							if(!$member['sex']){
								$member_update['sex']=$fans['sex'];
							}
							if($member_update){
								$this->member_update($uid,$member_update);
							}
						}
					}else{
						if($checkid){
							//把会员密码，账号加到已有账户
							if($member['password']){
									$upmember=array(
										'password'=>$member['password'],
										'username'=>$member['username']
									);
									pdo_update('core_members',$upmember,array('uniacid'=>$_SESSION['uniacid'],'id'=>$checkid));
							}
							pdo_delete('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$uid));
							$uid=$checkid;
						}
					}
				}elseif($_SESSION['container']=='alipay'){
					//支付宝环境
				}
			}elseif($_SESSION['os']=='wxapp'){
					//微信小程序
					$fans=pdo_get('core_fans',array('uniacid'=>$_SESSION['uniacid'],'type'=>1,'wxgid'=>$_SESSION['wxapp_id'],'openid'=>$_SESSION['openid']),array('id','mid','unionid','avatar','nickname','sex'));
					$checkid=0;
					//先判断是不是关联公众号
					if($fans['unionid']){
						$member=pdo_get('core_members',array('id <>'=>$uid,'uniacid'=>$_SESSION['uniacid'],'unionid'=>$fans['unionid']),array('id','onemid'));
						$checkid=$member['onemid']>0?$member['onemid']:$member['id'];
					}
					if($fans['mid'] && !$checkid){
						$checkid=pdo_getcolumn('core_members',array('id'=>$fans['mid']),'id');
					}					
					if($fans['id'] && !$checkid){
						pdo_update('core_fans',array('mid'=>$uid),array('uniacid'=>$_SESSION['uniacid'],'id'=>$fans['id']));
						if($fans['avatar'] && $fans['nickname']){
							$member=pdo_get('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$uid),array('nickname','avatar','sex'));
							$member_update=array();
							if(!$member['nickname']){
								$member_update['nickname']=$fans['nickname'];
							}
							if(!$member['avatar']){
								$member_update['avatar']=$fans['avatar'];
							}
							if(!$member['sex']){
								$member_update['sex']=$fans['sex'];
							}
							if($member_update){
								$this->member_update($uid,$member_update);
							}
						}
					}else{
						//把会员密码，账号加到已有账户
						if($checkid){
							if($member['password']){
									$upmember=array(
										'password'=>$member['password'],
										'username'=>$member['username']
									);
									pdo_update('core_members',$upmember,array('uniacid'=>$_SESSION['uniacid'],'id'=>$checkid));
							}
							pdo_delete('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$uid));
							$uid=$checkid;
						}
					}
			}elseif($_SESSION['os']=='ttapp'){
				//头条小程序
				$fans=pdo_get('core_fans',array('uniacid'=>$_SESSION['uniacid'],'type'=>1,'ttgid'=>$_SESSION['ttapp_id'],'openid'=>$_SESSION['openid']),array('id','mid','avatar','nickname','sex'));
				$checkid=pdo_getcolumn('core_members',array('id'=>$fans['mid']),'id');
				if($fans && !$checkid){
					pdo_update('core_fans',array('mid'=>$uid),array('id'=>$fans['id']));
					if($fans['avatar'] && $fans['nickname']){
							$member=pdo_get('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$uid),array('nickname','avatar','sex'));
							$member_update=array();
							if(!$member['nickname']){
								$member_update['nickname']=$fans['nickname'];
							}
							if(!$member['avatar']){
								$member_update['avatar']=$fans['avatar'];
							}
							if(!$member['sex']){
								$member_update['sex']=$fans['sex'];
							}
							if($member_update){
								$this->member_update($uid,$member_update);
							}
					}
				}else{
					if($checkid){
						//把会员密码，账号加到已有账户
						if($member['password']){
								$upmember=array(
									'password'=>$member['password'],
									'username'=>$member['username']
								);
								pdo_update('core_members',$upmember,array('uniacid'=>$_SESSION['uniacid'],'id'=>$checkid));
						}
						pdo_delete('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$uid));
						$uid=$checkid;
					}
				}
			}elseif($_SESSION['os']=='aliapp'){
				//支付宝小程序
				$fans=pdo_get('core_fans',array('uniacid'=>$_SESSION['uniacid'],'type'=>1,'aligid'=>$_SESSION['aliapp_id'],'openid'=>$_SESSION['openid']),array('id','mid','avatar','nickname','sex'));
				$checkid=pdo_getcolumn('core_members',array('id'=>$fans['mid']),'id');
				if($fans && !$checkid){
					pdo_update('core_fans',array('mid'=>$uid),array('id'=>$fans['id']));
					if($fans['avatar'] && $fans['nickname']){
							$member=pdo_get('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$uid),array('nickname','avatar','sex'));
							$member_update=array();
							if(!$member['nickname']){
								$member_update['nickname']=$fans['nickname'];
							}
							if(!$member['avatar']){
								$member_update['avatar']=$fans['avatar'];
							}
							if(!$member['sex']){
								$member_update['sex']=$fans['sex'];
							}
							if($member_update){
								$this->member_update($uid,$member_update);
							}
					}
				}else{
					if($checkid){
						//把会员密码，账号加到已有账户
						if($member['password']){
								$upmember=array(
									'password'=>$member['password'],
									'username'=>$member['username']
								);
								pdo_update('core_members',$upmember,array('uniacid'=>$_SESSION['uniacid'],'id'=>$checkid));
						}
						pdo_delete('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$uid));
						$uid=$checkid;
					}
				}
			}elseif($_SESSION['os']=='baiduapp'){
				//百度小程序
				$fans=pdo_get('core_fans',array('uniacid'=>$_SESSION['uniacid'],'type'=>1,'baidugid'=>$_SESSION['baiduapp_id'],'openid'=>$_SESSION['openid']),array('id','mid','sex','avatar','nickname'));
				$checkid=pdo_getcolumn('core_members',array('id'=>$fans['mid']),'id');
				if($fans && !$checkid){
					pdo_update('core_fans',array('mid'=>$uid),array('id'=>$fans['id']));
					if($fans['avatar'] && $fans['nickname']){
							$member=pdo_get('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$uid),array('nickname','avatar','sex'));
							$member_update=array();
							if(!$member['nickname']){
								$member_update['nickname']=$fans['nickname'];
							}
							if(!$member['avatar']){
								$member_update['avatar']=$fans['avatar'];
							}
							if(!$member['sex']){
								$member_update['sex']=$fans['sex'];
							}
							if($member_update){
								$this->member_update($uid,$member_update);
							}
					}
				}else{
					if($checkid){
						//把会员密码，账号加到已有账户
						if($member['password']){
								$upmember=array(
									'password'=>$member['password'],
									'username'=>$member['username']
								);
								pdo_update('core_members',$upmember,array('uniacid'=>$_SESSION['uniacid'],'id'=>$checkid));
						}
						pdo_delete('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$uid));
						$uid=$checkid;
					}
				}
			}
		}
		//如果手机注册
		if($member['mobile']){
			$uid=$this->merge_memberdata($member['mobile'],$uid);
		}
		//发生事件
		publish('core','member.register',array('mid'=>$uid));
		model('core/member')->login($uid);
		return $uid;
	}
	public function wechat_auth_base_url(){
		$_SESSION['isauth_base']=1;
		$_SESSION['isauth_info']=0;
		$backurl=urlencode(download_url('core/member.auth/base'));
		if($_SESSION['container']=='wxwork'){
			$wechat=pdo_get('core_account_wxwork',array('id'=>$_SESSION['wxwork_id']));
			$wechat['appsecret']=pdo_getcolumn('core_account_wxwork_app',array('id'=>$_SESSION['wxworkapp_id']),'appsecret');
		}else{
			$wechat=pdo_get('core_account_wechat',array('id'=>$_SESSION['wechat_id']));
			if($wechat['type'] !=4 && $_SESSION['auth_wxid']){
				$wechat=pdo_get('core_account_wechat',array('id'=>$_SESSION['auth_wxid']));
			}
		}
		if(!$wechat['appid']){
			return false;
		}
		$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$wechat['appid'].'&redirect_uri='.$backurl.'&response_type=code&scope=snsapi_base&state=getcode#wechat_redirect';
		return $url;
	}
	public function wechat_auth_info_url(){
		if($_SESSION['openid']){
			$backurl=urlencode(download_url('core/member.auth/info'));
			if($_SESSION['container']=='wxwork'){
				$wechat=pdo_get('core_account_wxwork',array('id'=>$_SESSION['wxwork_id']));
				$wechat['appsecret']=pdo_getcolumn('core_account_wxwork_app',array('id'=>$_SESSION['wxworkapp_id']),'appsecret');
			}else{
				$wechat=pdo_get('core_account_wechat',array('id'=>$_SESSION['wechat_id']));
				if($wechat['type'] !=4 && $_SESSION['auth_wxid']){
					$wechat=pdo_get('core_account_wechat',array('id'=>$_SESSION['auth_wxid']));
				}
			}
			if(!$wechat['appid']){
				return false;
			}
			$_SESSION['isauth_info']=1;
			if($_SESSION['this']=='manage'){
				$files=array('id','uniacid','expires_time','refresh_time','access_token','refresh_token');
				$fans=pdo_get('core_open_user',array('open_uid'=>$_SESSION['openid']),$files);
				//如果已经存在粉丝，且已经获取过用户信息,一个月刷新一次
				$user=pdo_get('core_users',array('id'=>$fans['uniacid']),array('nickname','avatar','upfanstime'));
				if($user['nickname'] && $user['avatar'] && $user['upfanstime']+30*24*3600>TIMESTAMP){
					cfc('user')->login($fans['uniacid']);
					return false;
				}
				//刷新token作用域为snsapi_userinfo，防止跟snsapi_base的token冲突，不需要缓存！
				/*if($fans['access_token'] && TIMESTAMP>$fans['expires_time'] && $fans['refresh_time']>TIMESTAMP){			
					model('core/fans_api')->up_openinfo('info');
					return false;
				}elseif($fans['access_token'] && $fans['expires_time']>TIMESTAMP){//2小时内,直接读取
					model('core/fans_api')->up_openinfo('info');
					return false;
				}*/
			}else{				
				$files=array('id','nickname','avatar','sex','pcd','updatetime','mid','unionid','expires_time','refresh_time','access_token','refresh_token');
				$fans=pdo_get('core_fans',array('openid'=>$_SESSION['openid'],'uniacid'=>$_SESSION['uniacid'],'wxgid'=>$_SESSION['wechat_id']),$files);
				if($fans['nickname'] && $fans['avatar'] && $fans['updatetime']+30*24*3600>TIMESTAMP){
					$member=pdo_get('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$fans['mid']),array('id','onemid'));
					$mid=$member['onemid']>0?$member['onemid']:$member['id'];
					//如果粉丝的unionid，跟会员一直，也说明已经注册了。
					if($fans['unionid']){
						$member=pdo_get('core_members',array('uniacid'=>$_SESSION['uniacid'],'unionid'=>$fans['unionid']),array('id','onemid'));
						$unionidmid=$member['onemid']>0?$member['onemid']:$member['id'];
					}
					if($mid){
						model('core/member')->login($mid);
					}elseif($unionidmid){
						model('core/member')->login($unionidmid);
						pdo_update('core_fans',array('mid'=>$unionidmid),array('id'=>$fans['id']));
					}else{
						$data=array_fields(array('nickname','avatar','sex','unionid','pcd'),$fans);
						model('core/member')->register($data);
					}					
					return false;
				}
				//刷新token作用域为snsapi_userinfo，防止跟snsapi_base的token冲突，不需要缓存！
				/*if($fans['access_token'] && TIMESTAMP>$fans['expires_time'] && $fans['refresh_time']>TIMESTAMP){			
					model('core/fans_api')->up_userinfo('info');
					return false;
				}elseif($fans['access_token'] && $fans['expires_time']>TIMESTAMP){//2小时内,直接读取
					model('core/fans_api')->up_userinfo('info');
					return false;
				}*/
			}
			//该定时刷新粉丝信息了
			$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$wechat['appid'].'&redirect_uri='.$backurl.'&response_type=code&scope=snsapi_userinfo&state=getcode#wechat_redirect';
			return $url;
		}else{
			//没用OPENID时，先获取openid
			$url = $this->wechat_auth_base_url();
			return $url;
		}
	}
	public function ali_auth_base_url(){
		$_SESSION['isauth_base']=1;
		$_SESSION['isauth_info']=0;
		$backurl=urlencode(download_url('core/member.auth/base'));
		$aliapp=pdo_get('core_account_wxapp',array('id'=>$_SESSION['aliapp_id']));
		if(!$aliapp['ali_appid']){
			return false;
		}
		$url='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.$aliapp['ali_appid'].'&redirect_uri='.$backurl.'&response_type=code&scope=auth_base&state=getcode#aliapp_redirect';
		return $url;
	}
	public function ali_auth_info_url(){
		if($_SESSION['openid']){
			$backurl=urlencode(download_url('core/member.auth/info'));
			$aliapp=pdo_get('core_account_wxapp',array('id'=>$_SESSION['aliapp_id']));
			if(!$aliapp['ali_appid']){
				return false;
			}
			$_SESSION['isauth_info']=1;
			if($_SESSION['this']=='manage'){
				$files=array('id','uniacid','expires_time','refresh_time','access_token','refresh_token');
				$fans=pdo_get('core_open_user',array('open_uid'=>$_SESSION['openid']),$files);
				//如果已经存在粉丝，且已经获取过用户信息,一个月刷新一次
				$user=pdo_get('core_users',array('id'=>$fans['uniacid']),array('nickname','avatar','upfanstime'));
				if($user['nickname'] && $user['avatar'] && $user['upfanstime']+30*24*3600>TIMESTAMP){
					cfc('user')->login($fans['uniacid']);
					return false;
				}
			}else{				
				$files=array('id','nickname','avatar','sex','pcd','updatetime','mid','unionid','expires_time','refresh_time','access_token','refresh_token');
				$fans=pdo_get('core_fans',array('openid'=>$_SESSION['openid'],'uniacid'=>$_SESSION['uniacid'],'aligid'=>$_SESSION['aliapp_id']),$files);
				if($fans['nickname'] && $fans['avatar'] && $fans['updatetime']+30*24*3600>TIMESTAMP){
					$member=pdo_get('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$fans['mid']),array('id','onemid'));
					$mid=$member['onemid']>0?$member['onemid']:$member['id'];
					//如果粉丝的unionid，跟会员一直，也说明已经注册了。
					if($fans['unionid']){
						$member=pdo_get('core_members',array('uniacid'=>$_SESSION['uniacid'],'unionid'=>$fans['unionid']),array('id','onemid'));
						$unionidmid=$member['onemid']>0?$member['onemid']:$member['id'];
					}
					if($mid){
						model('core/member')->login($mid);
					}elseif($unionidmid){
						model('core/member')->login($unionidmid);
						pdo_update('core_fans',array('mid'=>$unionidmid),array('id'=>$fans['id']));
					}else{
						$data=array_fields(array('nickname','avatar','sex','unionid','pcd'),$fans);
						model('core/member')->register($data);
					}				
					return false;
				}
			}
			//该定时刷新粉丝信息了
			$url='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.$aliapp['ali_appid'].'&redirect_uri='.$backurl.'&response_type=code&scope=auth_userinfo&state=getcode#aliapp_redirect';
			return $url;
		}else{
			//没用OPENID时，先获取openid
			$url = $this->ali_auth_base_url();
			return $url;
		}
	}
	/*
		获取详情
	*/
	public function detail($mid,$fields=array(),$noauth=false){
		global $_RQ,$_AR;
		if(!$mid){
			return array();
		}
		$available_fields=$this->available_fields();
		$fields=array_intersect($available_fields,$fields);
		$detail=pdo_get('core_members',array('id'=>$mid),$fields);
		if(empty($detail)){
			return array();
		}
		$wechat=model('core/web')->get_auth_wechat($_SESSION['uniacid']);
		if(!$_SESSION['isauth_info'] && !$noauth && $mid==$_SESSION['uid'] && $wechat && $_SESSION['container']=='wechat' && ($_RQ['is_access'] || defined('IN_WQZ'))){
			//微信端访问页面，页面需要获取昵称头像等信息时，尝试发起获取粉丝信息授权
			if((in_array('avatar',$fields) && !$detail['avatar']) || (in_array('nickname',$fields) && !$detail['nickname'])){
				//处于微信环境
				$url=$this->wechat_auth_info_url();
				if(defined('IN_WQZ')){
					$_SESSION['after_auth_url']=$_AR['siteurl'];
					if($url){
						header('location:'.$url);
						exit;
					}
				}else{
					$_SESSION['after_auth_url']=custom_url($_AR['access_json'],true);
					if($url){
						exi('','',$url);
					}
				}
				
			}
		}
		$detail['avatar']=$detail['avatar']?tomedia($detail['avatar']):tomedia('../core/resource/images/noavatar.gif');
		return $detail;
	}
	/*
		获取credit
	*/
	public function creditdata($member){
		$credit_types=credit_types();
		$creditdata=array();
		$payset=uni_setting('pay');
		foreach($credit_types as $k=>$title){
			$creditkey='credit'.$k;
			$rate=$payset['credit'.$k.'_rate']?:1;
			$creditdata[]=array('rate'=>$rate,'type'=>$k,'field'=>$creditkey,'title'=>$title,'value'=>$member[$creditkey]);
		}
		return $creditdata;
	}
	/*
		更新数据
	*/
	public function member_update($mid,$update=array()){
		$available_fields=$this->available_fields(true);
		foreach($update as $key=>$value){
			if(!in_array($key,$available_fields)){
				unset($update[$key]);
			}
		}
		pdo_update('core_members',$update,array('id'=>$mid));
		return true;
	}
	/*
		更新unionid
	*/
	public function add_unionid($mid,$unionid='',$isup=false){
		if(!$unionid || !$mid){
			return false;
		}
		$isadd=pdo_getcolumn('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$mid),'unionid');
		if($isadd && !$isup){
			return false;
		}
		pdo_update('core_members',array('unionid'=>$unionid),array('uniacid'=>$_SESSION['uniacid'],'id'=>$mid));
		return true;
	}
	public function available_fields($update=false){
		$available_fields=array('groupid','fromuser','from_os','createtime','mobile','username','unionid','nickname','avatar','qq','wechat','address','birth','pcd','sex','realname','email');
		if(!$update){
			$available_fields[]='credit1';
			$available_fields[]='credit2';
		}
		return $available_fields;
	}
	/*
		付款给顾客
	*/
	public function pay_out($mid,$params){
		if(!$mid || !$params){
			exi('付款失败！参数错误！','error');
		}
		if(!$params['money'] || $params['money']<=0){
			exi('付款失败！付款金额必须大于0');
		}
		if(!$params['remark']){
			exi('付款失败！必须设置付款备注！','error');
		}
		$money=round($params['money'],2);
		$pay_out=array(
			'uniacid'=>$_SESSION['uniacid'],
			'trade_no'=>get_ordersn('core_payout_log','trade_no','OUT'),
			'mid'=>$mid,
			'money'=>$money,
			'createtime'=>TIMESTAMP,
			'remark'=>$params['remark'],
			'status'=>0,
		);
		pdo_insert('core_payout_log',$pay_out);
		$pay_id=pdo_insertid();
		$data=array(
			'mch_billno'=>$pay_out['trade_no'],
			'openid'=>$pay_out['mid'],
			'money'=>$pay_out['money'],
			'remark'=>$pay_out['remark'],
		);
		$res=model('core/wechat_pay')->mch_pay($data);
		if($res['return_code']!='SUCCESS' || $res['result_code']!='SUCCESS'){
			exi("打款失败！具体原因为：{$return['return_msg']}|{$return['err_code']}|{$return['err_code_des']}",'error');
		}
		$update=array(
			'status'=>1,
			'pay_type'=>'wechat',
			'out_trade_no'=>$res['payment_no'],
		);
		pdo_update('core_payout_log',$update,array('id'=>$pay_id));
		return $pay_id;
	}
	/*
		发红包给顾客
	*/
	public function payred_out($mid,$params){
		if(!$mid || !$params){
			return error('发红包失败！参数错误！');
		}
		if(!$params['money'] || $params['money']<=0){
			return error('发红包失败！付款金额必须大于0');
		}
		if(!$params['remark']){
			return error('发红包失败！必须设置付款备注！');
		}
		$money=round($params['money'],2);
		$pay_out=array(
			'uniacid'=>$_SESSION['uniacid'],
			'trade_no'=>get_ordersn('core_payout_log','trade_no','OUT'),
			'mid'=>$mid,
			'money'=>$money,
			'createtime'=>TIMESTAMP,
			'remark'=>$params['remark'],
			'status'=>0,
		);
		pdo_insert('core_payout_log',$pay_out);
		$pay_id=pdo_insertid();
		$data=array(
			'mch_billno'=>$pay_out['trade_no'],
			'send_name'=>$_SESSION['account']['title'],
			'openid'=>$pay_out['mid'],
			'money'=>$pay_out['money'],
			'remark'=>$pay_out['remark'],
		);
		$res=model('core/wechat_pay')->redpack($data);
		if($res['return_code']!='SUCCESS' || $res['result_code']!='SUCCESS'){
			return error("发红包失败！具体原因为：{$return['return_msg']}|{$return['err_code']}|{$return['err_code_des']}");
		}
		$update=array(
			'status'=>1,
			'pay_type'=>'wechat',
			'out_trade_no'=>$res['payment_no'],
		);
		pdo_update('core_payout_log',$update,array('id'=>$pay_id));
		return $res;
	}
	/*
		获取简略信息
	*/
	public function basic($mid){
		$member=pdo_get('core_members',array('id'=>intval($mid)),array('nickname','mobile','avatar','credit1','credit2'));
		return $member?:array();
	}
	public function get_address_str($address_id,$en='',$userinfo=''){
		if(is_array($address_id)){
			$address=$address_id;
		}else{
			$address=pdo_get('core_address',array('id'=>$address_id));
		}
		$address['pcd']=$address['pcd']?json_decode($address['pcd'],true):array();
		$address_str=$address['pcd']['province'].' '.$address['pcd']['city'].' '.$address['pcd']['district'].' '.$address['pcd']['street'].' '.$address['address'];
		if($en){
			$address_str=$address['address'].' '.$address['pcd']['district'].' '.$address['pcd']['city'].' '.$address['pcd']['province'].' '.$address['pcd']['countries'];
		}
		if($userinfo){
			$address_userinfo=$address['name'].','.$address['mobile'];
			$address_str=$address_userinfo.','.$address_str;
		}
		return $address_str;
	}
	
	/*
		积分余额变更,$tag用于区分来源
	*/
	public function member_credit($mid,$field,$value,$is_add='',$from_plugin='',$remark='',$tag='',$op_mid=0){
		$fields=array('credit1','credit2','credit3','credit4','credit5','credit6','credit2_fz');
		if(!in_array($field,$fields)){
			return error('要修改的字段不被允许修改');
		}
		if(!$remark){
			exi('请设置变更积分余额的备注！','error');
		}
		if($is_add){
			$data=array($field.' +='=>$value);
		}else{
			$fieldfee=pdo_getcolumn('core_members',array('id'=>$mid,'uniacid'=>$_SESSION['uniacid']),$field);
			if($fieldfee<$value){
				return false;
			}else{
				$data=array($field.' -='=>$value);
			}
		}
		pdo_update('core_members',$data,array('id'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		$type=substr($field, -1);
		$log=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'type'=>$type,
			'is_add'=>$is_add?1:0,
			'fee'=>$value,
			'remark'=>$remark,
			'plugin'=>$from_plugin,
			'tag'=>$tag,
			'op_mid'=>$op_mid,
			'createtime'=>TIMESTAMP
		);
		pdo_insert('core_credit_log',$log);
		$log_id=pdo_insertid();
		return $log_id;
	}
	//增加积分
	public function add_credit1($mid,$money,$remark='',$from_plugin='',$tag=''){
		return $this->member_credit($mid,'credit1',$money,true,$from_plugin,$remark,$tag);
	}
	//增加余额
	public function add_credit2($mid,$money,$remark='',$from_plugin=''){
		return $this->member_credit($mid,'credit2',$money,true,$from_plugin,$remark);
	}
	//减少积分
	public function cut_credit1($mid,$money,$remark='',$from_plugin=''){
		return $this->member_credit($mid,'credit1',$money,false,$from_plugin,$remark);
	}
	//减少余额
	public function cut_credit2($mid,$money,$remark='',$from_plugin=''){
		return $this->member_credit($mid,'credit2',$money,false,$from_plugin,$remark);
	}
	//提现申请冻结
	public function fz_credit2($mid,$money,$remark='',$from_plugin=''){
		return $this->member_credit($mid,'credit2_fz',$money,true,$from_plugin,$remark);
	}
	//提现申请解冻
	public function thaw_credit2($mid,$money,$remark='',$from_plugin=''){
		return $this->member_credit($mid,'credit2_fz',$money,false,$from_plugin,$remark);
	}
	public function member_show($mid,$default_url='',$default=false){
		
		$member=pdo_get('core_members',array('id'=>intval($mid)),array('id','nickname','username','mobile','avatar','from_os'));
		if(!$member){
			$member=$default?:array('nickname'=>'无');
		}else{
			$member['url']=$default_url?str_replace('{mid}',$member['id'],$default_url):'';
			$member['nickname']=$member['nickname']?:$member['username'];
		}
		return $member;
	}
	//随机虚拟用户
	public function rand_xuni(){
		$members=pdo_getall('core_members',array('uniacid'=>$_SESSION['uniacid'],'is_virtual'=>1),'id');
		$count = count($members);
		$index = rand(1,$count);
		if($count>0){
			return $members[$index]['id'];
		}else{
			return false;
		}
	}
	//认证手机号，统一会员数据（积分，余额）,最老的为onemid
	public function merge_memberdata($mobile,$mid=0,$oldmobile=''){
		$mid=$mid?:$_SESSION['uid'];
		if(strlen($mobile)!=11 || $mobile[0]!='1' || !is_numeric($mobile)){
			return $mid;
		}
		$allmembers=pdo_getall('core_members',array('uniacid'=>$_SESSION['uniacid'],'realmobile'=>$mobile),'','','id asc');
		if(!$allmembers || count($allmembers)==0){
			return $mid;
		}
		$member=$allmembers[0];
		unset($allmembers[0]);
		$mid=$member['id'];
		if(!$allmembers || count($allmembers)==0){
			return $mid;
		}
		$credit1=0;$credit2=0;
		foreach($allmembers as $mv){
			$credit1 +=$mv['credit1'];
			$credit2 +=$mv['credit2'];
			$member['nickname']=$member['nickname']?:$mv['nickname'];
			$member['avatar']=$member['avatar']?:$mv['avatar'];
			$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mv['id']);
			//更新数据
			pdo_update('core_address',array('mid'=>$mid),$params);
			pdo_update('core_member_cash',array('mid'=>$mid),$params);
			pdo_update('core_credit_log',array('mid'=>$mid),$params);
			pdo_update('core_ideal_money_inlog',array('mid'=>$mid),$params);
			//更新粉丝
			pdo_update('core_fans',array('mid'=>$mid),$params);
			//电商客
			if(model('core/core')->plugin_exists('jy_weishop')){
				pdo_update('jy_weishop_order',array('mid'=>$mid),$params);
				pdo_update('jy_weishop_order_goods',array('mid'=>$mid),$params);
			}
		}
		$update=array(
			'credit1 +='=>$credit1,
			'credit2 +='=>$credit2,
			'nickname'=>$member['nickname'],
			'avatar'=>$member['avatar'],
			'onemid'=>0,
		);
		pdo_update('core_members',$update,array('uniacid'=>$_SESSION['uniacid'],'id'=>$mid));
		pdo_update('core_members',array('onemid'=>$mid,'credit1'=>0,'credit2'=>0),array('uniacid'=>$_SESSION['uniacid'],'id <>'=>$mid,'realmobile'=>$mobile));
		//插入日志
		$indate=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$_SESSION['uid'],
			'onemid'=>$mid,
			'newmobile'=>$mobile,
			'oldmobile'=>$oldmobile,
			'createtime'=>TIMESTAMP,
		);
		pdo_insert('core_members_log',$indate);
		return $mid;
	}
}